<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="../js/vue.js"></script>
    <title>Document</title>
</head>

<body>
    <div id="root">
        <h2>人员列表</h2>
        <input type="text" placeholder="请输入名字" v-model="keyWord">
        <ul>
            <li v-for="(item,index) in computePersons" :key="item.id">{{item.name}}-{{item.age}}-{{item.sex}} </li>
        </ul>
    </div>
    <script>
        Vue.config.productionTip = false; //以阻止vue在启动时生成生产提示
        new Vue({
            el: "#root",
            data: {
                keyWord: "",
                persons: [{
                        id: "001",
                        name: "马冬梅",
                        age: 18,
                        sex: '女'
                    },
                    {
                        id: "002",
                        name: "周冬雨",
                        age: 19,
                        sex: '女'
                    },
                    {
                        id: "003",
                        name: "周杰伦",
                        age: 20,
                        sex: '男'
                    },
                    {
                        id: "004",
                        name: "温兆伦",
                        age: 21,
                        sex: '男'
                    },
                ],
                filterPersons: []
            },
            mounted() {
                // this.filterPersons = this.persons//这样也是不太好的,watch我们直接刚上来立即执行不就完了嘛,computed本来就是上来或者一变化就计算
            },
            // (1).方法一computed
            computed: {
                computePersons() {
                    return this.filterPersons = this.persons.filter((p) => { //filter返回的是原数组
                        return p.name.indexOf(this.keyWord) != -1 //return 后边是条件,符合则返回,不符合则不返回
                    })
                }
            },

            // 我们不是说过只要是computed能做的watch也可以做,所以我们现在用watch做一下看看
            // (2).方法二watch

            // watch: {
            //     keyWord: {
            //         immediate: true,
            //         handler(val) {
            //             this.filterPersons = this.persons.filter((p) => { //filter返回的是原数组
            //                 return p.name.indexOf(val) != -1 //return 后边是条件,符合则返回,不符合则不返回
            //             })
            //         }
            //     }
            // }
        })
    </script>

</body>

</html>